//
//  CZNewFeatureViewController.swift
//  czbkiosweibo5
//
//  Created by zhangping on 15/10/14.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class CZNewFeatureViewController: UICollectionViewController {
    
    // MARK: - 属性
    private let itemCount = 4
    
    // 流水布局
    private var layout = UICollectionViewFlowLayout()
    
    // 将collection view layout 封装在内部,别人调用的时候不需要来关心layout的设置
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册cell
        self.collectionView!.registerClass(CZNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 准备layout
        prepareLayout()
    }
    
    /**
    准备CollectionView 的layout
    */
    private func prepareLayout() {
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }

    // MARK: - collectionView 代理和数据源
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZNewFeatureCell
    
        // 设置当前cell是第几个cell
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    /// cell显示完毕,得到的是离开屏幕,看不到的cell的indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
//        print("cell显示完: indexPath: \(indexPath)")
        // 得到的cell不是我们想要的.
        // 获取正在显示的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        
        // 判断是不是最后一页
        if indexPath?.item == itemCount - 1 {
            // 根据indexPath获取cell
            let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! CZNewFeatureCell
            
            // 开始动画
            cell.showStartButton()
        }
    }
}

// MARK: - 自定义cell
class CZNewFeatureCell: UICollectionViewCell {
    
    // 不同页面显示不同图片.
    var imageIndex: Int? = 0 {
        // 当collectionView 来设置imageIndex的时候,根据imageIndex去加载图片
        didSet {
            backgroundImageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
            
            // 每当显示cell的时候都隐藏开始体验按钮
            startButton.hidden = true
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 准备UI
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 开始按钮动画
    /**
    开始体验按钮动画
    */
    func showStartButton() {
        // 开始动画时,在显示按钮
        startButton.hidden = false
        
        // 使用transform来动画
        startButton.transform = CGAffineTransformMakeScale(0, 0)
    
        // 动画
        UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }, completion: { (_) -> Void in
//                print("开始体验 动画结束")
        })
    }
    
    // 开始体验 按钮点击事件
    func startClick() {
//        (UIApplication.sharedApplication().delegate as? AppDelegate)?.switchViewController(true)
        AppDelegate.switchViewController(true)
    }
    
    // MARK: - 准备UI
    private func prepareUI() {
        // 添加子控件
        contentView.addSubview(backgroundImageView)
        contentView.addSubview(startButton)
        
        // 添加约束
        backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 背景视图 填充父控件
        backgroundImageView.ff_Fill(contentView)
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bg" : backgroundImageView]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bg" : backgroundImageView]))
        
        // 开始按钮
        // 内部,底部向上160
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
        
        // X 
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
    }
    
    // MARK: - 懒加载控件
    // 背景图片
    private lazy var backgroundImageView = UIImageView()
    
    // 开始按钮
    private lazy var startButton: UIButton = {
        let button = UIButton()

        // 设置背景
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置文字
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        // 隐藏按钮, 在这里隐藏会因为cell复用,在第2页也出现开始体验按钮
//        button.hidden = true
        
        // 添加事件
        button.addTarget(self, action: "startClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}